package com.aijk.web.admin.controller.h5;


import com.aijk.commons.utils.Utils;
import com.aijk.ehm.api.BasHealthAssessmentApi;
import com.aijk.ehm.model.BasHealthAssessment;
import com.aijk.ehm.model.qo.BasHealthAssessmentQo;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Controller
@RequestMapping(value = "/h5")
public class H5Controller {



    @Autowired
    private BasHealthAssessmentApi basHealthAssessmentApi;


    @RequestMapping(value = "health/assessment")
    public Object health_assessment(BasHealthAssessment healthAssessment, HttpServletRequest request, Model model) throws Exception {
       // BasHealthAssessment healthAssessment=new BasHealthAssessment();
        //healthAssessment.setUid();
        System.out.print("11111111111111===="+healthAssessment.getUid()+"------------------");
        BasHealthAssessmentQo basHealthAssessmentQo1 = new BasHealthAssessmentQo();
        basHealthAssessmentQo1.setSortway("created desc");
        basHealthAssessmentQo1.setUid(healthAssessment.getUid());
        basHealthAssessmentQo1.setStatus(true);
        List<BasHealthAssessment> assessmentList1 = basHealthAssessmentApi.list(basHealthAssessmentQo1);
        if (assessmentList1 != null && !assessmentList1.isEmpty()) {
            if((healthAssessment!=null&&healthAssessment.getUid()!=null&&healthAssessment.getUid()!=0)|| StringUtils.isEmpty(request.getHeader("uid"))){
                Map<String,BasHealthAssessment> assessmentMap = new HashMap<>();
                for(BasHealthAssessment assessment:assessmentList1){
                    assessmentMap.put(assessment.getQuestionnaireId().toString(),assessment);
                }
                model.addAttribute("assessment",assessmentMap);
                model.addAttribute("exited",true);
            }else{
                model.addAttribute("exited",true);
            }
        }else {
            model.addAttribute("exited",true);
        }
        model.addAttribute("uid", healthAssessment.getUid());
        System.out.print("222222222222222===="+healthAssessment.getUid()+"------------------");
        return "h5/health_index";
    }


    @RequestMapping(value = "health/base")
    public Object health_base(BasHealthAssessment healthAssessment, Model model) throws Exception {
        List<BasHealthAssessment> assessmentList = getAssessList(healthAssessment);
        System.out.print("333333333333333===="+healthAssessment.getUid()+"------------------");

        if (assessmentList.size() == 1) {
            model.addAttribute("result", assessmentList.get(0).getResult());
        }
        /*args.clear();
        args.put("uid",healthAssessment.getUid());
        List<MedResident> residents =  residentService.findAll(args);*/
       /* if(residents.size()>0&&!StringUtils.isEmpty(residents.get(0).getIdcard())){
            args.clear();
            args.put("idcard",residents.get(0).getIdcard());
           List<MedResidentEhrWithBLOBs> ehrs = ehrService.findAll(args);
            if(ehrs.size()>0&&!ehrs.get(0).getJMJBXX().equals("[]")){
                JSONArray jsonArray =  JSONObject.parseArray(ehrs.get(0).getJMJBXX().replace("@de", "de").replace("#text", "text").replace("@display", "display"));
                System.out.println(((JSONObject)jsonArray.get(0)).get("CNAME_SEX"));
                JSONObject json=(JSONObject)jsonArray.get(0);
                if(!StringUtils.isEmpty(json.getJSONObject("BIRTHDAY").getString("text"))){
                    json.put("age", DateUtil.getAge(DateUtil.getDate(json.getJSONObject("BIRTHDAY").getString("text"))));
                }
                if(!StringUtils.isEmpty(json.getJSONObject("MARRIAGE").getString("text"))){
                    if(json.getJSONObject("MARRIAGE").getString("text").equals("1")){
                        json.put("MARRIAGE","未婚");
                    }else if (json.getJSONObject("MARRIAGE").getString("text").equals("2")){
                        json.put("MARRIAGE","已婚");
                    }else{
                        json.put("MARRIAGE","无");
                    }

                }

                model.addAttribute("jmjbxx", jsonArray.get(0));

            }
        }*/
        model.addAttribute("uid", healthAssessment.getUid());
        System.out.print("44444444444444===="+healthAssessment.getUid()+"------------------");
        return "h5/health_base";
    }

    @RequestMapping(value = "health/family")
    public Object health_family(BasHealthAssessment healthAssessment, Model model) {
        List<BasHealthAssessment> assessmentList = getAssessList(healthAssessment);
        System.out.print("555555555555555===="+healthAssessment.getUid()+"------------------");
        if (assessmentList.size() == 1) {
            model.addAttribute("result", assessmentList.get(0).getResult());
        }
        model.addAttribute("uid", healthAssessment.getUid());
        System.out.print("666666666666666===="+healthAssessment.getUid()+"------------------");
        return "h5/health_family";
    }

    @RequestMapping(value = "health/lifestyle")
    public Object health_lifestyle(BasHealthAssessment healthAssessment, Model model) {
        System.out.print("333333333333333===="+healthAssessment.getUid()+"------------------");
        List<BasHealthAssessment> assessmentList = getAssessList(healthAssessment);
        if (assessmentList.size() == 1) {
            model.addAttribute("result", assessmentList.get(0).getResult());
        }
        model.addAttribute("uid", healthAssessment.getUid());
        System.out.print("333333333333333===="+healthAssessment.getUid()+"------------------");
        return "h5/health_lifestyle";
    }

    @RequestMapping(value = "health/psychological")
    public Object health_psychological(BasHealthAssessment healthAssessment, Model model) {
        List<BasHealthAssessment> assessmentList = getAssessList(healthAssessment);

        if (assessmentList.size() == 1) {
            model.addAttribute("result", assessmentList.get(0).getResult());
        }
        model.addAttribute("uid", healthAssessment.getUid());
        return "h5/health_psychological";
    }

    @RequestMapping(value = "health/old")
    public Object health_health_old(BasHealthAssessment healthAssessment, Model model) {
        List<BasHealthAssessment> assessmentList = getAssessList(healthAssessment);

        if (assessmentList.size() == 1) {
            model.addAttribute("result", assessmentList.get(0).getResult());
        }
        model.addAttribute("uid", healthAssessment.getUid());
        return "h5/health_old";
    }

    @RequestMapping(value = "health/assessment/save")
    public void health_assessment_save(HttpServletResponse response,
                                       BasHealthAssessment healthAssessment,
                                       String questionArray) throws IOException {
        Integer questionnaire_id = healthAssessment.getQuestionnaireId();
        Integer uid = healthAssessment.getUid();
        System.out.print("88888888888888===="+uid+"------------------"+questionnaire_id);
        System.out.print("7777777777777777===="+healthAssessment.getUid()+"------------------");
        BasHealthAssessmentQo basHealthAssessmentQo = new BasHealthAssessmentQo();
        basHealthAssessmentQo.setUid(uid);
        basHealthAssessmentQo.setQuestionnaireId(questionnaire_id);
        basHealthAssessmentApi.delete(basHealthAssessmentQo); //先删除之前的资料



        healthAssessment.setIdtree("#" + questionnaire_id);
        healthAssessment.setCreated(new Date());
        basHealthAssessmentApi.save(healthAssessment); // 保存结果

        if (Utils.isNotEmpty(questionArray)) { // 保存问题与答案
            JSONArray questions = JSON.parseArray(questionArray);

            for (int i = 0; i < questions.size(); i++) {
                BasHealthAssessment answers = new BasHealthAssessment();
                answers.setPid(questionnaire_id);
                answers.setUid(uid);

                JSONObject question = questions.getJSONObject(i);

                if (question.containsKey("answer")) {
                    JSONArray answerArray = question.getJSONArray("answer");
                    for (int j = 0; j < answerArray.size(); j++) {
                        JSONObject answer = answerArray.getJSONObject(j);
                        if (Utils.isNotEmpty(answer.get("answer"))) {
                            Integer questionNo = Utils.toInteger(question.get("question_no"));
                            Integer answerNo = Utils.toInteger(answer.get("answer_no"));

                            answers.setQuestionNo(questionNo);
                            answers.setQuestion(question.get("question").toString());
                            answers.setAnswerNo(answerNo);
                            answers.setAnswer(answer.get("answer").toString());
                            answers.setIdtree("#" + questionnaire_id + "#" + questionNo + "#" + answerNo);
                            answers.setCreated(new Date());
                            basHealthAssessmentApi.save(answers);
                        }
                    }
                }
                if (question.containsKey("hide")) { // 保存隐藏问题与答案
                    JSONObject hideJSONObject = question.getJSONObject("hide");
                    if (hideJSONObject.containsKey("answer")) {
                        JSONArray hideAnswerArray = hideJSONObject.getJSONArray("answer");
                        for (int k = 0; k < hideAnswerArray.size(); k++) {
                            JSONObject hideAnswerJSON = hideAnswerArray.getJSONObject(k);

                            Integer hideQuestionNo = Utils.toInteger(hideJSONObject.get("question_no"));
                            Integer hidePid = Utils.toInteger(hideJSONObject.get("question_pid"));
                            String hideQuestion = hideJSONObject.get("question").toString();
                            Integer hideAnswerNo = Utils.toInteger(hideAnswerJSON.get("answer_no"));
                            String hideAnswer = hideAnswerJSON.get("answer").toString();
                            String idTree = "#" + questionnaire_id + "#" + hidePid + "#" + hideQuestionNo + "#" + hideAnswerNo;

                            answers.setQuestionPid(hidePid);
                            answers.setQuestionNo(hideQuestionNo);
                            answers.setQuestion(hideQuestion);
                            answers.setAnswerNo(hideAnswerNo);
                            answers.setAnswer(hideAnswer);
                            answers.setIdtree(idTree);
                            answers.setUid(uid);
                            answers.setCreated(new Date());
                            basHealthAssessmentApi.save(answers);
                        }
                    }
                }
                /*//保存红点消息
                args.clear();
                args.put("uid",uid);
                List<MedResident> residents = residentService.findAll(args);
                if(residents != null && residents.size() > 0){
                    MedResident resident = residents.get(0);
                    //检查是否有未读红点消息没有进行新增
                    args.clear();
                    args.put("ecn",resident.getEcn());
                    args.put("category","1301");
                    args.put("status",10);
                    List<SysMessage> sysMessages = messageService.findAll(args);
                    if(sysMessages == null || sysMessages.size() == 0){
                        appMessageHandler.createResidentMessage(args,"ecn","1301","健康评估报告消息");
                    }
                }*/
            }
            response.getWriter().print("1");
        }
    }

    private List<BasHealthAssessment> getAssessList(BasHealthAssessment healthAssessment) {
        BasHealthAssessmentQo basHealthAssessmentQo = new BasHealthAssessmentQo();
        basHealthAssessmentQo.setUid(healthAssessment.getUid());
        basHealthAssessmentQo.setQuestionnaireId(healthAssessment.getQuestionnaireId());
        return basHealthAssessmentApi.list(basHealthAssessmentQo);
    }

}

